package com.shopx.gw.interceptor;

import com.shopx.base.exception.OriginException;
import com.shopx.core.common.CommonConstant;
import com.shopx.core.context.ShopxContext;
import com.shopx.core.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lituo
 * @className: BuildInterceptor
 * @description: TODO
 * @date 2021/12/2 1:59 PM
 */
@Slf4j
public class ShopxInterceptor implements HandlerInterceptor {

  @Value("${file.oss.secret}")
  private String secret;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    String accessUrl = request.getServletPath();
    String trcId = StringUtil.createRandomCharData(32);
    MDC.put(CommonConstant.TRACE_ID, trcId);
    if(accessUrl.indexOf("error")>-1 || accessUrl.indexOf("oss/staticFile")>-1){
      return true;
    }
    //自定义拦截器权限
    String hmac = request.getHeader("hmac");
    if(!hmac.equals(secret)){
      throw new OriginException("权限不合法，上传失败");
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                         ModelAndView modelAndView) throws Exception {
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    String accessUrl = request.getServletPath();
    log.info("方法:{}执行结束。",accessUrl);
    MDC.remove(CommonConstant.TRACE_ID);
    ShopxContext ctx = ShopxContext.getCurrentContext();
    if (ctx != null) {
      // 清除上下文
      ctx.removeCurrentContext();
      ctx.clear();
    }
  }
}
